package logic

import (
	"context"
	"fmt"
	"meituan-waimai/models/mysql"

	"meituan-waimai/meituanrpc/internal/svc"
	"meituan-waimai/meituanrpc/meituanrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CouponReceiveLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCouponReceiveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CouponReceiveLogic {
	return &CouponReceiveLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CouponReceiveLogic) CouponReceive(in *meituanrpc.CouponReceiveRequest) (*meituanrpc.CouponReceiveResponse, error) {
	// todo: add your logic here and delete this line
	//优惠券领取

	//判断是否已经领取过
	var coupon mysql.Coupon
	mysql.DB.Where("id = ?", in.CouponId).First(&coupon)
	if coupon.UserId != 0 {
		return nil, fmt.Errorf("优惠券已被领取")
	}

	coupon.UserId = int(in.UserId)
	mysql.DB.Updates(&coupon)
	return &meituanrpc.CouponReceiveResponse{}, nil
}
